<?php

namespace Controller;

use Lib\Request,
    Lib\Util\Session;

class AdminPages extends Admin {

    public function index() {
        $this->title .= ' &raquo; Странице';
        
        $this->loadModel('Page');
        $this->set('pages', $this->Page->find());
    }

    public function edit($id) {
        $this->index();

        $page = $this->Page->get($id);
        if (! $page && $id>0) {
            $this->redirect('/admin_pages');
        }

        $this->set('page', $page);
        $this->set('backgrounds', App::bodyBackgrounds());

        echo $this->render('index');
    }

    public function create() {
        $this->edit(0);
    }

    public function save() {
        $data = Request::post('data');
        $url = '/admin_pages';
        if (! empty($data)) {
            $this->loadModel('Page');
            $id = (int)$data->id;

            if ($this->Page->save($data)) {
                Session::flash('Страница је сачувана.', 'ok');
            } else {
                Session::flash($this->Page->errors, 'error');
            }

            if ($id<1) {
                $id = $this->Page->lastInsertId;
            }
            $url = '/admin_pages/edit/' . $id;
        }

        $this->redirect($url);
    }

    public function delete($id) {
        if ($id>0) {
            $this->loadModel('Page');
            if ($this->Page->delete($id)) {
                Session::flash('Страница је обрисана', 'error');
            } else {
                Session::flash('Страница није обрисана');
            }
        }

        $this->redirect('/admin_pages');
    }

    public function order() {
        $data = Request::get('data');
        if (! empty($data)) {
            $this->loadModel('Page');
            foreach ($data as $id=>$position) {
                $this->Page->save(array(
                    'id' => $id,
                    'position' => $position
                ));
            }
        }

        $this->redirect('/admin_pages');
    }

}